package com.ccys.doctor.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.ccys.common.util.Kit;
import com.ccys.db.cache.UserUtil;
import com.ccys.db.dto.doctor.pendToConsult.CreateOfflineBookingDto;
import com.ccys.db.entity.*;
import com.ccys.db.mapper.*;
import com.ccys.doctor.service.BookingAllergiesService;
import com.ccys.doctor.service.ConsultStageService;
import com.ccys.doctor.service.PendingToConsultService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author：XLY
 * @Date：2024/3/5 0005
 */
@Service
public class PendingToConsultServiceImpl implements PendingToConsultService {


    @Resource
    private TblMemberMapper memberMapper;


    @Resource
    private TblDoctorMapper doctorMapper;


    @Resource
    private TblPricingTimingMapper pricingTimingMapper;


    @Resource
    private TblBookingMapper bookingMapper;



    @Resource
    private TblBookingSummaryMapper summaryMapper;

    @Resource
    private TblBookingFeeMapper bookingFeeMapper;

    @Resource
    private TblBookingConsultationMapper bookingConsultationMapper;


    @Resource
    private TblMemberAllergiesMapper memberAllergiesMapper;


    @Resource
    private BookingAllergiesService bookingAllergiesService;


    @Resource
    private TblBookingMemberInfoMapper bookingMemberInfoMapper;



    @Transactional
    @Override
    public void createOfflineBooking(CreateOfflineBookingDto dto) {
        // TODO: 2024/3/2 0002 费用计算
        String mem_id = dto.getMem_id();
        String child_id = dto.getChild_id();
        mem_id = StringUtils.isNotEmpty(child_id)?child_id:mem_id;
        //查询国家
        Example memberExample = new Example(TblMember.class);
        memberExample.createCriteria().andEqualTo("delFlag",0).andEqualTo("id","'"+mem_id+"'");
        TblMember memberInfo = memberMapper.selectOneByExample(memberExample);

        //根据国家确定时区
        String countryOfResidence = memberInfo.getCurrentCountry();
        String timezoneStr = "+8:00";
        Integer timezone = 8;
        if ("106".equals(countryOfResidence) || "245".equals(countryOfResidence)  || "41".equals(countryOfResidence)) {
            timezoneStr = "+7:00";
            timezone = 7;
        }
        //设置默认国家
        List<String> notInCountries = Arrays.asList("203", "106", "245", "41", "136");
        if (!notInCountries.contains(String.valueOf(countryOfResidence))) {
            countryOfResidence = "203";
        }
        //获取当前星期几，注意0-星期一，以此类推6-星期天
        int dayOfTheWeek = Kit.getWhatDayIsToday(timezone);
        //total_cost_consulation
        BigDecimal total_cost_consulation = pricingTimingMapper.getMaxValueByOfficeType(timezoneStr, countryOfResidence, dayOfTheWeek);
        //surcharge_fee
        BigDecimal surcharge_fee = new BigDecimal(0);
        BigDecimal practice_fee = new BigDecimal(0);
        //standard fee
        BigDecimal standardFee = practice_fee.add(surcharge_fee).add(total_cost_consulation);
        //taxRate
        BigDecimal taxRate = new BigDecimal(0);
        Integer taxRateType = 0;;
        //@total_amount
        BigDecimal totalAmount = new BigDecimal(0);
        //@payment_amount
        BigDecimal paymentAmount = totalAmount;


        //API_CreateOfflineBooking
        //doctor相关
        Example doctorExample = new Example(TblDoctor.class);
        String curLoginUserId = UserUtil.getCurLoginUserId();
        doctorExample.createCriteria().andEqualTo("delFlag",0).andEqualTo("id","'"+ curLoginUserId +"'");
        TblDoctor doctor = doctorMapper.selectOneByExample(doctorExample);
        //doctor fee
        //@doctor_type_pharma_type
        //有关的字段全部删除了


        //member相关
        //计算患者age
        Date dob = memberInfo.getDob();
        Date currentDate = new Date();
        Integer memberAge = (int) DateUtil.betweenYear(dob, currentDate, false);

        //Insert tbl_Booking(按照函数的顺序)
        TblBooking booking = new TblBooking();
        booking.setConsultationNo(IdUtil.getSnowflakeNextIdStr());
        booking.setMemId(mem_id);
        booking.setDoctorId(curLoginUserId);
        booking.setPatientMemId(child_id);
        booking.setMemberAge(memberAge);
        booking.setStatus(3);
        booking.setSubStatus(0);
        booking.setMemType(StringUtils.isNotEmpty(child_id)?2:1);

        TblBookingFee bookingFee = new TblBookingFee();
        bookingFee.setStandardFee(standardFee);
        bookingFee.setTotalAmount(totalAmount);
        bookingFee.setTaxRate(taxRate);
        bookingFee.setTaxRateType(taxRateType);

        booking.setConsultationMode(5);
        booking.setPaidPrescription(0);
        booking.setClinicId(doctor.getCurrentClinicId());

        bookingFee.setDeliveryFee(new BigDecimal(0));
        bookingFee.setConsultationFee(total_cost_consulation);
        bookingFee.setWaiveConsultationFeeFlag(0);
        bookingFee.setWaiveConsultationFee(new BigDecimal(0));

        TblBookingSummary summary = new TblBookingSummary();
        summary.setG6pd(memberInfo.getG6pd());
        summary.setPregnant(memberInfo.getPregnant());
        //如果standardfee没有值，surchargeFee有值那就是1
        int isSurcharge = Objects.isNull(total_cost_consulation) ? 1 : 0;
        bookingFee.setIsSurcharge(isSurcharge);
        bookingFee.setTotalAmountPaid(new BigDecimal(0));

        summary.setNeedMedicalLetter(0);
        summary.setNeedMedicalCertification(0);

        bookingFee.setPracticeFee(practice_fee);
        booking.setAddDeliveryFee(0);
        booking.setCompanyId(doctor.getCompanyId());


        String bookingId = IdUtil.getSnowflakeNextIdStr();
        //booking的id = summary的id
        bookingFee.setBookingId(bookingId);
        booking.setId(bookingId);
        summary.setId(bookingId);
        bookingFeeMapper.insert(bookingFee);
        bookingMapper.insert(booking);
        summaryMapper.insert(summary);

        //tbl_Booking_Consultation
        TblBookingConsultation bookingConsultation = new TblBookingConsultation();
        bookingConsultation.setBookingId(bookingId);
        bookingConsultation.setBeginTime(currentDate);
        bookingConsultation.setEndTime(currentDate);
        bookingConsultation.setAmount(total_cost_consulation);
        bookingConsultation.setStatus(1);
        bookingConsultation.setOrdering(0);
        bookingConsultation.setType(1);
        // 创建一个Calendar对象，并设置为UTC时区
        Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
        // 使用Calendar对象获取UTC时间的Date对象
        Date utcDate = calendar.getTime();
        bookingConsultation.setBeginTimeUtc(utcDate);
        bookingConsultation.setEndTimeUtc(utcDate);
        bookingConsultationMapper.insert(bookingConsultation);

        //Allergies && medication reaction
        Example memberAllergiesExample = new Example(TblMemberAllergies.class);
        memberAllergiesExample.createCriteria().andEqualTo("memId",mem_id).andEqualTo("delFlag",0);
        List<TblMemberAllergies> memberAllergies = memberAllergiesMapper.selectByExample(memberAllergiesExample);
        List<TblBookingAllergies> collect = memberAllergies.stream().map(x -> {
            TblBookingAllergies model = new TblBookingAllergies();
            model.setBookingId(bookingId);
            model.setAllergiesName(x.getAllergiesName());
            model.setMedicationReactionId(x.getMedicationReactionId());
            model.setId(IdUtil.getSnowflakeNextIdStr());
            return model;
        }).collect(Collectors.toList());
        //批量添加
        bookingAllergiesService.insertAll(collect);

        //booking member info
        //memberInfo 是parent
        Example childExample = new Example(TblMember.class);
        childExample.createCriteria().andEqualTo("delFlag",0).andEqualTo("id",child_id);
        TblMember childInfo = memberMapper.selectOneByExample(childExample);
        TblBookingMemberInfo bookingMember = new TblBookingMemberInfo();
        bookingMember.setBookingId(bookingId);
        bookingMember.setMemberDob(memberInfo.getDob());
        bookingMember.setMemberEmail(memberInfo.getEmail());
        bookingMember.setMemberFirstName(memberInfo.getFirstName());
        bookingMember.setMemberLastName(memberInfo.getLastName());
        bookingMember.setMemberId(memberInfo.getId());
        bookingMember.setMemberNricFin(memberInfo.getNricFin());
        bookingMember.setMemberGender(memberInfo.getGender());
        bookingMember.setMemberPhoneNumber(memberInfo.getPhone());
        if(Objects.nonNull(childInfo)){
            bookingMember.setChildDob(childInfo.getDob());
            bookingMember.setChildEmail(childInfo.getEmail());
            bookingMember.setChildFirstName(childInfo.getFirstName());
            bookingMember.setChildLastName(childInfo.getLastName());
            bookingMember.setChildGender(childInfo.getGender());
            bookingMember.setChildId(childInfo.getId());
            bookingMember.setChildNricFin(childInfo.getNricFin());
            bookingMember.setChildPhoneNumber(childInfo.getPhone());
        }

         bookingMemberInfoMapper.insert(bookingMember);

    }
}
